package com.yygo.dao.hibernate;

import com.yygo.Constants;
import com.yygo.dao.BankDao;
import com.yygo.model.Bank;
import com.yygo.model.LoanProduct;
import com.yygo.model.User;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Created by tiansha on 2015/8/6.
 */
@Repository("bankDao")
public class BankDaoHibernate extends GenericDaoHibernate<Bank, Long> implements BankDao {

    public BankDaoHibernate() {
        super(Bank.class);
    }

    @Override
    public List<Bank> getAllBanks() {
        Criteria criteria = getSession().createCriteria(Bank.class).add(Restrictions.eq("deleted", false));
        return criteria.list();
    }

    @Override
    public Set<LoanProduct> getLoanProductsByBank(Long bankId) {
        Bank bank = get(bankId);
        for (LoanProduct loanProduct : bank.getLoanProducts()) {
            loanProduct.getId();
        }
        return bank.getLoanProducts();
    }

    @Override
    public Bank save(Bank bank) {
        getSession().saveOrUpdate(bank);
        // necessary to throw a DataIntegrityViolation and catch it in UserManager
        getSession().flush();
        return bank;
    }

    public List<User> getUsers(Long bankId) {
        Bank bank = super.get(bankId);
        List<User> users = new ArrayList<>();
        for (User user : bank.getUsers()) {
            user.getUsername();
            //if (user.hasRole(Constants.Bank_USER_ROLE) || user.hasRole(Constants.Bank_RECEIVER_ROLE))
                users.add(user);
        }

        return users;
    }
}
